package com.haotunet.app.goldtreasure.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.activity.DynamicDetailActivity;
import com.haotunet.app.goldtreasure.adapter.MainPagerAdapter;
import com.haotunet.app.goldtreasure.cycleviewpager.lib.CycleViewPager;
import com.haotunet.app.goldtreasure.cycleviewpager.lib.CycleViewPager.ImageCycleViewListener;
import com.haotunet.app.goldtreasure.model.BannerInfo;
import com.haotunet.app.goldtreasure.model.BannerModel;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.MsgInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.net.UrlUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.other.ViewFactory;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.views.HoveringScrollView;
import com.haotunet.app.goldtreasure.views.HoveringScrollView.OnScrollListener;
import com.haotunet.app.goldtreasure.views.TitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class FoundFragment extends BaseFragment implements OnScrollListener, OnPageChangeListener {
    @InjectView(R.id.title_view_found)
    TitleView titleViewFound;
    @InjectView(R.id.banner_layout)
    LinearLayout bannerLayout;
    @InjectView(R.id.tv_infomation)
    TextView tvInfomation;
    @InjectView(R.id.tv_media_report)
    TextView tvMediaReport;
    @InjectView(R.id.tv_dynamic)
    TextView tvDynamic;
    @InjectView(R.id.iv_info_line)
    ImageView ivInfoLine;
    @InjectView(R.id.iv_media_line)
    ImageView ivMediaLine;
    @InjectView(R.id.iv_dynamic_line)
    ImageView ivDynamicLine;
    @InjectView(R.id.tab_layout_views)
    LinearLayout tabLayoutViews;
    @InjectView(R.id.float_layout_two)
    LinearLayout floatLayoutTwo;
    @InjectView(R.id.vp_found)
    ViewPager vpFound;
    @InjectView(R.id.hoveringScrollView)
    HoveringScrollView hoveringScrollView;
    @InjectView(R.id.float_layout_one)
    LinearLayout floatLayoutOne;
    private View view;
    private CycleViewPager cycleViewPager;
    private boolean isPrepared;
    private boolean mHasLoadedOnce;
    private final int STATUS_BANNER_SUCCESS = 4;
    private TextView tv_menu[];
    private List<ImageView> ivList;
    private MediaFragment mediaFragment;
    private ShareStore shareStore;
    private int prePosition = 0;
    private Handler handle = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {

                case STATUS_BANNER_SUCCESS:
                    BannerModel bannerModel = (BannerModel) msg.obj;
                    List<BannerInfo> bannerList = bannerModel.getDiscoveryBannerList();
                    if (bannerList.size() > 0) {
                        setBannerInfo(bannerList);
                    }
                    break;
                default:
                    break;
            }
        }

    };

    public static FoundFragment newInstance() {
        Bundle args = new Bundle();
        FoundFragment fragment = new FoundFragment();
        fragment.setArguments(args);
        return fragment;
    }

    public FoundFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_found, null);
        ButterKnife.inject(this, view);
        shareStore = new ShareStore(getActivity());
        initView();
        isPrepared = true;
        return view;
    }

    private void initView() {

        titleViewFound.getTitletextView().setVisibility(View.VISIBLE);
        titleViewFound.getTitletextView().setText(getString(R.string.main_menu4_txt));
        titleViewFound.getGuideView().setVisibility(View.VISIBLE);
        titleViewFound.getNotificationView().setVisibility(View.VISIBLE);
        cycleViewPager = (CycleViewPager) getActivity().getFragmentManager()
                .findFragmentById(R.id.fragment_cycle_viewpager);
        ivList = new ArrayList<>();
        ivList.add(ivInfoLine);
        ivList.add(ivMediaLine);
        ivList.add(ivDynamicLine);
        vpFound = (ViewPager) view.findViewById(R.id.vp_found);
        tv_menu = new TextView[3];
        tv_menu[0] = tvInfomation;
        tv_menu[1] = tvMediaReport;
        tv_menu[2] = tvDynamic;
        for (int i = 0; i < tv_menu.length; i++) {
            final int cur = i;
            tv_menu[i].setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    setTabview(cur);
                }
            });
        }
        Fragment[] fragment = new Fragment[3];
        mediaFragment = MediaFragment.newInstance(2);
        fragment[0] = mediaFragment;
        fragment[1] = MediaReportFragment.newInstance(3);
        fragment[2] = MediaFragment.newInstance(1);
        MainPagerAdapter adapter = new MainPagerAdapter(getChildFragmentManager());
        adapter.add(fragment[0]);
        adapter.add(fragment[1]);
        adapter.add(fragment[2]);
        vpFound.setAdapter(adapter);
        hoveringScrollView.setOnScrollListener(this);
        vpFound.addOnPageChangeListener(this);
        vpFound.setOffscreenPageLimit(adapter.getCount());
        setTabview(0);
    }

    protected void setBannerInfo(List<BannerInfo> bannerList) {
        List<ImageView> imageList = new ArrayList<>();
        imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(bannerList.size() - 1).getImageUrl()));

        for (int i = 0; i < bannerList.size(); i++) {
            imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(i).getImageUrl()));
        }
        // 将第一个ImageView添加进来
        imageList.add(ViewFactory.getImageView(getActivity(), bannerList.get(0).getImageUrl()));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(imageList, bannerList, mAdCycleViewListener);
        // 设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(3000);
        // 设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() {

        @Override
        public void onImageClick(BannerInfo info, int position, View imageView) {
            if (cycleViewPager.isCycle()) {
                position = position - 1;
                ActivityUtils.gotoDynamicDetail(getActivity(), info.getLinkUrl(), 1);
            }
        }

    };

    private void getBannerData() {
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getBannerData(2);
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (!isActivityAvailable()) {
                    return;
                }
                BannerModel bannerModel = (BannerModel) model;
                if (bannerModel == null) {
                    return;
                }
                if (bannerModel.getErrorMsg() != null) {
                    UIHelper.showToast(getActivity(), bannerModel.getErrorMsg());
                } else {
                    mHasLoadedOnce = true;
                    Message msg = new Message();
                    msg.what = STATUS_BANNER_SUCCESS;
                    msg.obj = bannerModel;
                    handle.sendMessage(msg);
                }
            }
        });
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible || mHasLoadedOnce) {
            requestUnreadMsg();
            return;
        }
        requestUnreadMsg();
        getBannerData();
        mediaFragment.getDiscoverNews(2, "0", "");
    }

    private void requestUnreadMsg() {
        if (shareStore.getBoolean(Strs.IS_LOGIN, false)) {
            getUnReadMsg();
        }
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= bannerLayout.getBottom()) {
            if (tabLayoutViews.getParent() != floatLayoutOne) {
                floatLayoutTwo.removeView(tabLayoutViews);
                floatLayoutOne.addView(tabLayoutViews);
            }
        } else {
            if (tabLayoutViews.getParent() != floatLayoutTwo) {
                floatLayoutOne.removeView(tabLayoutViews);
                floatLayoutTwo.addView(tabLayoutViews);
            }
        }
    }

    public void setTabview(int cur) {
        vpFound.setCurrentItem(cur, false);
        for (int i = 0; i < tv_menu.length; i++) {

            if (cur == i) {
                tv_menu[i].setSelected(true);
            } else {
                tv_menu[i].setSelected(false);
            }

        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    @SuppressWarnings("deprecation")
    @Override
    public void onPageSelected(int arg0) {
        ivList.get(prePosition).setBackgroundColor(getResources().getColor(R.color.color_white));
        ivList.get(arg0).setBackgroundColor(getResources().getColor(R.color.yellow_btn_bg));
        tv_menu[arg0].setTextColor(getResources().getColor(R.color.color_yellow));
        tv_menu[prePosition].setTextColor(getResources().getColor(R.color.color_black));
        prePosition = arg0;
    }

    private void getUnReadMsg() {
        ActionUtil actionUtil = new ActionUtil(getActivity());
        actionUtil.getUnReadMsg();
        actionUtil.setOnPassBackListener(new OnPassBackListener() {

            @Override
            public void passBack(BaseModel model) {
                if (!isActivityAvailable()) {
                    return;
                }
                MsgInfo msgInfo = (MsgInfo) model;
                if (msgInfo == null) {
                    return;
                }
                int unreadMsgCount = msgInfo.getUnreadMsgCount();
                if (unreadMsgCount != 0) {
                    titleViewFound.getNotificationView().setSelected(true);
                } else {
                    titleViewFound.getNotificationView().setSelected(false);
                }
            }
        });
    }

    public void switchTab(int type) {
        setTabview(type);
    }

    @SuppressWarnings("static-access")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6 && resultCode == getActivity().RESULT_OK) {
            requestUnreadMsg();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @OnClick({R.id.iv_notification, R.id.iv_flip, R.id.found_company_profile_layout, R.id.found_monthly_report_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_notification:
                Intent intent = new Intent();
                intent.setClass(getActivity(), DynamicDetailActivity.class);
                intent.putExtra("activityUrl", UrlUtil.MESSAGE_CENTER);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 6);
                break;
            case R.id.iv_flip:
                ActivityUtils.gotoNewGuideLines(getActivity());
                break;
            case R.id.found_company_profile_layout:
                ActivityUtils.gotoDynamicDetail(getActivity(), UrlUtil.ABOUT_US, 6);
                break;
            case R.id.found_monthly_report_layout:
                ActivityUtils.gotoDynamicDetail(getActivity(), UrlUtil.MONTHLY_OPERATION_REPORT_URL, 6);
                break;
        }
    }
}
